跳到主要内容

227 基本计算器 II

https://leetcode.cn/leetbook/read/top-interview-questions-hard/xwsg7t/

cost: 22m50s

class Solution {
public:
int calculate(string s) {
stack<char> operaters;
stack<int> operands;
for (int i = 0; i < s.size();) {
char ch = s[i];
if (ch == ' ') {
i++;
continue;
}
if (ch == '+' || ch == '-') {
if (!operaters.empty()) {
char op = operaters.top();
operaters.pop();
int v2 = operands.top();
operands.pop();
int v1 = operands.top();
operands.pop();
if (op == '+') {
v1 += v2;
} else {
v1 -= v2;
}
operands.push(v1);
}
operaters.push(ch);
i++;
continue;
}
if (ch == '*' || ch == '/') {
i++;
int v1 = operands.top();
operands.pop();
int v2 = this->parseInt(s, i);
if (ch == '*') {
v1 *= v2;
} else {
v1 /= v2;
}
operands.push(v1);
continue;
}
if (std::isdigit(ch)) {
int operand = this->parseInt(s, i);
operands.push(operand);
}
}
while (!operaters.empty()) {
char op = operaters.top();
operaters.pop();
int v2 = operands.top();
operands.pop();
int v1 = operands.top();
operands.pop();
if (op == '+') {
v1 += v2;
} else {
v1 -= v2;
}
operands.push(v1);
}
return operands.top();
}

private:
int parseInt(string& s, int& i) {
while (i < s.size() && s[i] == ' ') {
i++;
}
int res = 0;
while (i < s.size() && std::isdigit(s[i])) {
res *= 10;
res += s[i] - '0';
i++;
}
return res;
}
};